<?php
namespace App\Http\Controllers\Front;


use App\Models\Register;
use App\Models\RegUser;
use App\Models\UserPerformance;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Redis;
use App\Models\Keys;
use Curl\Curl;
use App\Models\CorpInfo;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use App\Models\RoleUser;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Input;
use App\Models\Company;


class IndexController extends Controller
{

    public function __construct()
    {
        
    }


    public function index(Request $request)
    {
        $suiteid = 'wwa27e2080fe46150f';
        $redirect_uri = urlencode('www.cimo.net/login');
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$suiteid.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect';
        return redirect($url);
    }

    //企业微信默认授权登录
    public function login(Request $request)
    {
        //session_start(); // 初始化session

        $suiteid = 'wwa27e2080fe46150f';
        $secret = 'iQkzSQD9RgLVsMRBUoua6w1rFc7RWoweF5ja_8QYAPY';
        $code = $request->input('code');
        $key = Keys::where('name','kh_suite_ticket')->orderBy('id','desc')->first()->value;
        $uri = 'https://qyapi.weixin.qq.com/cgi-bin/service/get_suite_token';
        $curl  =  new Curl();
        $data = array(
            'suite_id'    => $suiteid,
            'suite_secret'    => $secret,
            'suite_ticket'   => $key,
        );
        $data = json_encode($data);
        $curl->post($uri,$data);
        $suite_access_token = $curl->response->suite_access_token;
        $curl->close();
        //Log::info(['curl'=>$curl->response]);
        //Log::info(['key'=>$key]);
        //Log::info(['code'=>$code]);
        //Log::info(['token'=>$suite_access_token]);

        /*//预授权码
        $url_pre_auth_code = 'https://qyapi.weixin.qq.com/cgi-bin/service/get_pre_auth_code?suite_access_token='.$suite_access_token;
        $return_json_pre = json_decode(file_get_contents($url_pre_auth_code));
        $pre_auth_code = $return_json_pre->pre_auth_code;
        //dd($pre_auth_code);*/


        /*//获取企业永久授权码
        $url_permanent_code = 'https://qyapi.weixin.qq.com/cgi-bin/service/get_permanent_code?suite_access_token='.$suite_access_token;
        $curl_permanent_code  =  new Curl();
        $data_permanent_code = array(
            'auth_code'    => $code,
        );
        $data_permanent_code = json_encode($data_permanent_code);
        $curl_permanent_code->post($url_permanent_code,$data_permanent_code);
        $curl_permanent_code->close();
        dd($curl_permanent_code);
        $auth_corpid = $curl_permanent_code->auth_corp_info->corpid;//授权企业id

        $permanent_code = $curl_permanent_code->permanent_code;//授权企业永久码*/

        $url = 'https://qyapi.weixin.qq.com/cgi-bin/service/getuserinfo3rd?access_token='.$suite_access_token.'&code='.$code;
        $return_json = json_decode(file_get_contents($url));
        $user_ticket = $return_json->user_ticket;
        $auth_corpid = $return_json->CorpId;
        //Log::info(['key'=>$return_json]);

        /*$uri = 'https://qyapi.weixin.qq.com/cgi-bin/service/get_auth_info?suite_access_token='.$suite_access_token;
        $curl  =  new Curl();
        $data = array(
            'auth_corpid'    => $corpid,
            'permanent_code'    => $p_code,
        );
        $data = json_encode($data);
        $curl->post($uri,$data);
        $agentid = $curl->response->auth_info->agent[0]->agentid;
        $curl->close();*/
        //dd($agentid);
        /*//企业管理员列表
        $url_admin_list = 'https://qyapi.weixin.qq.com/cgi-bin/service/get_admin_list?suite_access_token='.$suite_access_token;
        $curl_admin_list  =  new Curl();
        $data_admin_list = array(
            'auth_corpid'    => $auth_corpid,
            'agentid'    => $agentid,
        );
        $data_admin_list = json_encode($data_admin_list);
        $curl_admin_list->post($url_admin_list,$data_admin_list);
        $curl_admin_list->close();
        $admin_list = $curl_admin_list->response->admin;//管理员列表json数组
        var_dump($admin_list);*/


        $corpinfo = CorpInfo::where('corpid',$auth_corpid)->orderBy('id','desc')->first();
        $auth_userid = $corpinfo->auth_userid;


        $detail_uri = 'https://qyapi.weixin.qq.com/cgi-bin/service/getuserdetail3rd?access_token='.$suite_access_token;
        $curl2  =  new Curl();
        $data2 = array(
            'user_ticket'    => $user_ticket,
        );
        $data2 = json_encode($data2);
        $curl2->post($detail_uri,$data2);
        $curl2->close();
        $userid = $curl2->response->userid;
        $username = $curl2->response->name;
        $gender = $curl2->response->gender;

        $user_exist = User::where('corpid',$auth_corpid)->where('qw_userid',$userid)->first();
        if(empty($user_exist)){
            $new = new User();
            $new->corpid = $auth_corpid;
            $new->qw_userid = $userid;
            $new->qw_name = $username;
            $new->gender = $gender;
            $new->save();

            $newregister = new Register();
            $newregister->name = 'qw_'.strtolower($userid).$new->id;
            $newregister->visual_password = '123456';
            $newregister->password = password_hash('123456', PASSWORD_DEFAULT);
            $newregister->type = 1;
            $newregister->save();

            $new_reguser = new RegUser();
            $new_reguser->register_id = $newregister->id;
            $new_reguser->user_id = $new->id;
            $new_reguser->corpid = $auth_corpid;
            $new_reguser->status = 1;
            $new_reguser->created_at =  date('Y-m-d H:i:s');
            $new_reguser->save();
            Auth::login($newregister);

            //用户为授权管理员，赋予系统管理员权限
            if($auth_userid == $userid){
                $role = new RoleUser();
                $role->corpid = $auth_corpid;
                $role->user_id = $new->id;
                $role->role_id = '9';
                $role->save();
            }

            //新建默认绩效记录
            $perf = new UserPerformance();
            $perf->user_id = $new->id;
            $perf->corpid = $auth_corpid;
            $perf->save();


        }else{
            $ru = RegUser::where('user_id',$user_exist->id)->where('corpid',$auth_corpid)->first();
            if($ru->status != 1){
                $ru->status = 1;
                $ru->save();
            }
            $user_exist->status = 1;
            $user_exist->save();
            $regi = Register::find($ru->register_id);
            Auth::login($regi);
        }
        return redirect('/jump');
    }

    public function jump()
    {
        $firstu = Auth::user();
        if(empty($firstu)){
            if($firstu->type == 1){
                abort(403,'登录失败');//企业微信用户
            }else{
                return  redirect('/front/login');
            }

        }
        $ru = RegUser::where('register_id',$firstu->id)->where('company_status','1')->whereIn('status',[1,3])->first();
        if(empty($ru)){
            $user = null;
        }else{
            $user = User::find($ru->user_id);
        }

        if(empty($user))
        {
            if($firstu->type == 1){
                abort(403,'登录失败');//企业微信用户
            }else{
                return  redirect('/front/start');//没有所属企业，没有申请,跳转进行申请或创建
            }
        }

        //申请中
        if($ru->status == 3){
            return redirect('front/wait');
        }

        //已经有企业
        //企业创建未完成
        if($ru->company_status == 0){
            return redirect('/admin/init/create');
        }

        if($ru->company_status != 1){
            abort(403,'公司状态有误');
        }
        //是否为系统管理员
        $role = RoleUser::where('role_id','9')->where('corpid',$user->corpid)->where('user_id',$user->id)->first();
        if(empty($role)){
            $com = Company::where('id',$user->corpid)->first();
            if(!empty($com) && $com->init_index == 2){
                if(time() > strtotime($com->expire_at)){
                    abort(403,'您的公司试用期已结束，请联系管理员购买服务');
                }
                return redirect('/user/performance/perf?uid='.$user->id);
            }else{
                abort(403, '您的公司管理员尚未初始化系统，请等待管理员初始化');
            }
        }else{
            $com = Company::where('id',$user->corpid)->first();
            if(empty($com)){
                if(Auth::user()->type== 1){
                    return redirect('/admin/init');
                }else{
                    return redirect('/admin/init/create');
                }

            }else{
                if($com->init_index == 2){
                    if(time() > strtotime($com->expire_at)){
                        if(is_mobile()){
                            return redirect('/cashier');
                        }else{
                            return redirect('/buy-vip');
                        }
                    }
                    return redirect('/sysadmin/permission/index');
                }else{
                    return redirect('/sysadmin/feedback/init');
                }

            }
        }

    }

    /*public function index()
    {
        $suiteid = 'wwa27e2080fe46150f';
        $redirect_uri = urlencode('kaohe.cimo.cn/user/performance/index');
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$suiteid.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect';
        return redirect($url);
    }*/

    public function echoMessage(Request $request)
    {
        include_once app_path('/thirdparty/weworkapi/callback/WXBizMsgCrypt.php');

        $encodingAesKey = "O2agp07JSgWBvVlGkAH32wb4Vdrj872FIGFjXgmIrnH";
        $token = "C2k3dqg";
        $corpId = "wwf24a6d690200562b";


        $sVerifyMsgSig = $request->input('msg_signature');
        $sVerifyTimeStamp = $request->input('timestamp');
        $sVerifyNonce = $request->input('nonce');
        $sVerifyEchoStr = $request->input('echostr');
        //return 'success';
          // 需要返回的明文
        $sEchoStr = "";

        $wxcpt = new \WXBizMsgCrypt($token, $encodingAesKey, $corpId);
        $errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
        if ($errCode == 0) {
            ob_clean();
            echo $sEchoStr;
            //return 'success';
            //
            // 验证URL成功，将sEchoStr返回
            // HttpUtils.SetResponce($sEchoStr);
        } else {
            print("ERR: " . $errCode . "\n\n");
        }
    }

    public function postMessage(Request $request)
    {
        include_once app_path('/thirdparty/weworkapi/callback/WXBizMsgCrypt.php');
        $encodingAesKey = "O2agp07JSgWBvVlGkAH32wb4Vdrj872FIGFjXgmIrnH";
        $token = "C2k3dqg";
        $corpId = "wwa27e2080fe46150f";
        $sMsg = '';
        $sVerifyMsgSig = $request->input('msg_signature');
        $sVerifyTimeStamp = $request->input('timestamp');
        $sVerifyNonce = $request->input('nonce');
        $sReqData = $request->getContent();
        //$sReqData = '<xml><ToUserName><![CDATA[wwa27e2080fe46150f]]></ToUserName><Encrypt><![CDATA[kus1aqv+37T45/5Fk+hsakDwBfpuiWT4UowBMSBM6Fo+uek3bSGetFeS2dD6G24J3ocLFkMk7U4IRFUNyQ/fvDgYgZvnSTTAN6WD9iISK3RNQRDh3rwb1jYVyUiwMxERcKmKqmp32vLszp+VcRQUvK5hORSH/c/+x5sSySXhJpeTQnA1jRQAMf63CVQTiHIYSIb+I5SFSyWpZd67z78PcFvrWHgh33S+Qx3LmrTWIk7U7x9Oomde4r8SUGNketPOGLwmEov7Nwpvd59tuukmSOdTyoxjFCRdUOcwbQ10LbWzDUI5hmtNsKliBeQggsS1kiVN6WOFzZ9mvRZiTLTA0R7cPXRiVMA+UvcVtR8RYKHiYEAgzDxX4HEPToH5BEOC]]></Encrypt><AgentID><![CDATA[]]></AgentID></xml>';
       // Log::info(['jilu'=>$sReqData]);
        $wxcpt = new \WXBizMsgCrypt($token, $encodingAesKey, $corpId);
        $errCode = $wxcpt->DecryptMsg($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sReqData, $sMsg);
        //dd($errCode);
        if ($errCode == 0) {
            // 解密成功，sMsg即为xml格式的明文
            //Log::info(['jilu'=>$sMsg]);
           // var_dump($sMsg);
            $xml = $sMsg;
            $objectxml = simplexml_load_string($xml,'SimpleXMLElement',LIBXML_NOCDATA);//将文件转换成 对象
            //var_dump($objectxml);
            $xmljson= json_encode($objectxml );//将对象转换个JSON
            $xmlarray=json_decode($xmljson,true);//将json转换成数组
            //dd($xmlarray['SuiteTicket']);
            //Redis::setex('kaohe_key',1200,$xmlarray['SuiteTicket']);
            switch ($xmlarray['InfoType']){
                case 'suite_ticket':
                    $kname = 'kh_suite_ticket';
                    $kvalue = $xmlarray['SuiteTicket'];
                    break;
                case 'create_auth':
                    $kname = 'kh_create_auth';
                    $kvalue = $xmlarray['AuthCode'];

                    $suiteid = 'wwa27e2080fe46150f';
                    $secret = 'iQkzSQD9RgLVsMRBUoua6w1rFc7RWoweF5ja_8QYAPY';
                    $key = Keys::where('name','kh_suite_ticket')->orderBy('id','desc')->first()->value;
                    $uri = 'https://qyapi.weixin.qq.com/cgi-bin/service/get_suite_token';
                    $curl  =  new Curl();
                    $data = array(
                        'suite_id'    => $suiteid,
                        'suite_secret'    => $secret,
                        'suite_ticket'   => $key,
                    );
                    $data = json_encode($data);
                    $curl->post($uri,$data);
                    $suite_access_token = $curl->response->suite_access_token;
                    $curl->close();
                    //获取企业永久授权码
                    $url_permanent_code = 'https://qyapi.weixin.qq.com/cgi-bin/service/get_permanent_code?suite_access_token='.$suite_access_token;
                    $curl_permanent_code  =  new Curl();
                    $data_permanent_code = array(
                        'auth_code'    => $kvalue,
                    );
                    $data_permanent_code = json_encode($data_permanent_code);
                    $curl_permanent_code->post($url_permanent_code,$data_permanent_code);
                    $curl_permanent_code->close();
                    //Log::info(['jilu'=>$curl_permanent_code]);
                    $auth_corpid = $curl_permanent_code->response->auth_corp_info->corpid;//授权企业id
                    $permanent_code = $curl_permanent_code->response->permanent_code;//授权企业永久码
                    $agentid = $curl_permanent_code->response->auth_info->agent[0]->agentid;
                    $auth_userid = $curl_permanent_code->response->auth_user_info->userid;
                    $key = new CorpInfo();
                    $key->corpid = $auth_corpid;
                    $key->permanent_code = $permanent_code;
                    $key->agentid = $agentid;
                    $key->auth_userid = $auth_userid;
                    $key->content = serialize($curl_permanent_code->response);
                    $key->save();
                    break;
                default:
                    $kname = 'kh_unknown';
                    $kvalue = serialize($xmlarray);
            }
            $key = new Keys();
            $key->name = $kname;
            $key->value = $kvalue;
            $key->save();
            /*if(!Redis::exists($key_prefix)){
                $this->options = $this->getJobsTypeOptions($ca_id);
                Redis::setex($key_prefix,86400,$this->options);
            }else{
                $this->options = Redis::get($key_prefix);
            }*/
            //Log::info(['jilu'=>$xmlarray['SuiteTicket']]);
            ob_clean();
            return 'success';
            // TODO: 对明文的处理
        } else {
            print("ERR: " . $errCode . "\n\n");
        }

    }
    

    public function echoMessage1(Request $request)
    {
        include_once app_path('/thirdparty/weworkapi/callback/WXBizMsgCrypt.php');

        $encodingAesKey = "O2agp07JSgWBvVlGkAH32wb4Vdrj872FIGFjXgmIrnH";
        $token = "C2k3dqg";
        $corpId = "wwf24a6d690200562b";


        $sVerifyMsgSig = $request->input('msg_signature');
        $sVerifyTimeStamp = $request->input('timestamp');
        $sVerifyNonce = $request->input('nonce');
        $sVerifyEchoStr = $request->input('echostr');

        // 需要返回的明文

        $sEchoStr = "";

        $wxcpt = new \WXBizMsgCrypt($token, $encodingAesKey, $corpId);
        $errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
        if ($errCode == 0) {
            ob_clean();
            echo $sEchoStr;
            //
            // 验证URL成功，将sEchoStr返回
            // HttpUtils.SetResponce($sEchoStr);
        } else {
            print("ERR: " . $errCode . "\n\n");
        }
    }


    public function first()
    {
        $fuser = Auth::user();
        if(empty($fuser)){
            return redirect('/front/login');
        }else{
            $reguser = RegUser::where('register_id',$fuser->id)->where('company_status','1')->whereIn('status',[1,3])->first();
            if(empty($reguser)){
                return redirect('/front/start');//申请或创建
            }
            if($reguser->status == 3){
                return redirect('/front/wait');//申请中
            }
            return redirect('/jump');
        }
    }


    public function xieyi()
    {
        return view('login.agreement');
    }
}

